<template>
  <view class="page message-page">
    <div class="page-title">我的消息 My Messages</div>
    <div class="wrap">
      <div class="ul">
        <div class="li" v-for="(item, index) in list" :key="item.id">
          <!-- <div class="text">{{ statusCn(item.type) + ':' + item.content }}</div> -->
          <div class="text">{{ item.content }}</div>
          <div class="date"></div>
        </div>
      </div>
      <uni-load-more :status="loading ? 'loading' : noMore ? 'noMore' : 'more'" />
    </div>
  </view>
</template>
<script setup lang="ts">
import { ref, reactive, getCurrentInstance, onMounted, watch, computed } from 'vue'
import { onLoad, onPullDownRefresh } from '@dcloudio/uni-app'
import { useStore } from 'vuex'

import { messageList, messageRead } from '@/utils/api/message'

console.log('messageRead', messageRead)
const store = useStore()

let current: number = 0
let size: number = 10

let list = ref<any>([])
let loading = ref<boolean>(false)
let noMore = ref<boolean>(false)
let refresh: boolean = false

// 1.支付成功 2.商品已发货 3.退款成功 4.发票信息 5.站内信

const statusCn = (status: number) => {
  const statusMap: Record<number, string> = {
    1: '已支付  Paid',
    2: '待收货  Delivered',
    3: '已退款  Refunded',
    4: '发票信息  InvoiceInfo',
    5: '站内信  Inbox'
  }
  return statusMap[status] || '未知状态'
}
const initData = async () => {
  if (loading.value || noMore.value) {
    return
  } else {
    loading.value = true
    const res = await messageList({
      current,
      size
    })
    uni.stopPullDownRefresh()
    loading.value = false
    if (res.code === 200) {
      let data = res.data
      // 先筛选再返回id
      let ids = data.list.filter((item: any) => item.isRead === 0).map((item: any) => item.id)
      if (ids.length && ids.length > 0) {
        readMessage(ids)
      }
      if (refresh) {
        list.value = data.list
        refresh = false
      } else {
        list.value = [...list.value, ...data.list]
      }
      if (data.next) {
        noMore.value = false
        current.value++
      } else {
        noMore.value = true
      }
    }
    console.log(res)
  }
}
onPullDownRefresh(() => {
  current = 0
  refresh = true
  noMore.value = false
  initData()
})
const readMessage = async (ids: Array<number>) => {
  console.log('readMessage')
  const { code, data } = await messageRead({ ids })
  if (code === 200) {
    console.log('readMessage success')
  } else {
    console.log('readMessage fail')
  }
}
onLoad(() => {
  initData()
})
</script>

<style lang="scss" scoped>
@import './message.scss';
</style>
